package cn.zhentao.controller;

import cn.zhentao.common.Result;
import cn.zhentao.dto.*;
import cn.zhentao.service.DigitalHumanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 数字人控制器
 * 提供数字人通话相关的REST API接口
 * 
 * @author zhentao
 */
@Slf4j
@RestController
@RequestMapping("/api/v2/digital-human")
@CrossOrigin(origins = "*")
public class DigitalHumanController {

    @Autowired
    private DigitalHumanService digitalHumanService;

    /**
     * 生成数字人通话实例
     * 
     * @param request 数字人通话请求
     * @return 数字人通话响应
     */
    @PostMapping("/generateCall")
    public Result<DigitalHumanCallResponseDto> generateDigitalHumanCall(@Valid @RequestBody DigitalHumanCallRequestDto request) {
        try {
            log.info("生成数字人通话实例请求: {}", request);
            
            DigitalHumanCallResponseDto response = digitalHumanService.generateDigitalHumanCall(request);
            
            if (response.getCode() == 200) {
                log.info("生成数字人通话实例成功: {}", response);
                return Result.success(response);
            } else {
                log.error("生成数字人通话实例失败: {}", response.getMessage());
                return Result.error(response.getMessage());
            }
        } catch (Exception e) {
            log.error("生成数字人通话实例异常: {}", e.getMessage(), e);
            return Result.error("生成数字人通话实例失败: " + e.getMessage());
        }
    }

    /**
     * 查询数字人实例信息
     * 
     * @param request 数字人实例查询请求
     * @return 数字人实例信息
     */
    @PostMapping("/describeInstance")
    public Result<DigitalHumanInstanceResponseDto> describeDigitalHumanInstance(@Valid @RequestBody DigitalHumanInstanceRequestDto request) {
        try {
            log.info("查询数字人实例信息请求: {}", request);
            
            DigitalHumanInstanceResponseDto response = digitalHumanService.describeDigitalHumanInstance(request);
            
            if (response.getCode() == 200) {
                log.info("查询数字人实例信息成功: {}", response);
                return Result.success(response);
            } else {
                log.error("查询数字人实例信息失败: {}", response.getMessage());
                return Result.error(response.getMessage());
            }
        } catch (Exception e) {
            log.error("查询数字人实例信息异常: {}", e.getMessage(), e);
            return Result.error("查询数字人实例信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取RTC认证Token
     * 
     * @param request RTC认证Token请求
     * @return RTC认证Token
     */
    @PostMapping("/getRtcAuthToken")
    public Result<RtcAuthTokenResponseDto> getRtcAuthToken(@Valid @RequestBody RtcAuthTokenRequestDto request) {
        try {
            log.info("获取RTC认证Token请求: {}", request);
            
            RtcAuthTokenResponseDto response = digitalHumanService.getRtcAuthToken(request);
            
            if (response.getCode() == 200) {
                log.info("获取RTC认证Token成功");
                return Result.success(response);
            } else {
                log.error("获取RTC认证Token失败: {}", response.getMessage());
                return Result.error(response.getMessage());
            }
        } catch (Exception e) {
            log.error("获取RTC认证Token异常: {}", e.getMessage(), e);
            return Result.error("获取RTC认证Token失败: " + e.getMessage());
        }
    }

    /**
     * 获取数字人配置信息
     * 
     * @return 数字人配置信息
     */
    @GetMapping("/config")
    public Result<Map<String, Object>> getDigitalHumanConfig() {
        try {
            Map<String, Object> config = new HashMap<>();
            
            // 支持的数字人类型
            config.put("supportedAgentTypes", new String[]{
                "AvatarAgent", "VideoAgent", "VisionAgent"
            });
            
            // 支持的语音ID
            config.put("supportedVoiceIds", new String[]{
                "zhixiaoxia", "zhichu", "zhimiao", "zhiyan"
            });
            
            // 默认配置
            config.put("defaultConfig", Map.of(
                "agentType", "AvatarAgent",
                "region", "cn-shanghai",
                "voiceId", "zhixiaoxia",
                "enableVoiceInterrupt", true,
                "enablePushToTalk", false,
                "sessionTimeout", 300
            ));
            
            // 数字人外观配置
            config.put("avatarConfig", Map.of(
                "backgroundColor", "#000000",
                "width", 512,
                "height", 512
            ));
            
            log.info("获取数字人配置信息成功");
            return Result.success(config);
        } catch (Exception e) {
            log.error("获取数字人配置信息异常: {}", e.getMessage(), e);
            return Result.error("获取数字人配置信息失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "digital-human");
        health.put("timestamp", System.currentTimeMillis());
        return Result.success(health);
    }

    /**
     * 兼容旧版API - 生成AI智能体通话
     * 为了兼容React前端的现有调用
     */
    @PostMapping("/generateAIAgentCall")
    public Result<Map<String, Object>> generateAIAgentCall(@RequestBody Map<String, Object> requestMap) {
        try {
            log.info("兼容API - 生成AI智能体通话请求: {}", requestMap);
            
            // 转换请求参数
            DigitalHumanCallRequestDto request = new DigitalHumanCallRequestDto();
            request.setUserId(requestMap.get("user_id").toString());
            request.setAiAgentId((String) requestMap.get("ai_agent_id"));
            request.setRegion((String) requestMap.getOrDefault("region", "cn-shanghai"));
            request.setAgentType((String) requestMap.getOrDefault("workflow_type", "AvatarAgent"));
            request.setUserData((String) requestMap.get("user_data"));
            request.setTemplateConfig((String) requestMap.get("template_config"));
            request.setAgentConfig((String) requestMap.get("agent_config"));
            request.setSessionId((String) requestMap.get("session_id"));
            request.setChatSyncConfig((String) requestMap.get("chat_sync_config"));
            
            if (requestMap.containsKey("expire")) {
                request.setExpire(Integer.valueOf(requestMap.get("expire").toString()));
            }
            
            DigitalHumanCallResponseDto response = digitalHumanService.generateDigitalHumanCall(request);
            
            if (response.getCode() == 200) {
                // 转换为兼容格式
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "success");
                result.put("ai_agent_instance_id", response.getAiAgentInstanceId());
                result.put("channel_id", response.getChannelId());
                result.put("ai_agent_user_id", response.getAiAgentUserId());
                result.put("rtc_auth_token", response.getRtcAuthToken());
                result.put("request_id", response.getRequestId());
                
                return Result.success(result);
            } else {
                return Result.error(response.getMessage());
            }
        } catch (Exception e) {
            log.error("兼容API - 生成AI智能体通话异常: {}", e.getMessage(), e);
            return Result.error("生成AI智能体通话失败: " + e.getMessage());
        }
    }

    /**
     * 兼容旧版API - 查询AI智能体实例
     */
    @PostMapping("/describeAIAgentInstance")
    public Result<Map<String, Object>> describeAIAgentInstance(@RequestBody Map<String, Object> requestMap) {
        try {
            log.info("兼容API - 查询AI智能体实例请求: {}", requestMap);
            
            DigitalHumanInstanceRequestDto request = new DigitalHumanInstanceRequestDto();
            request.setUserId(requestMap.get("user_id").toString());
            request.setAiAgentInstanceId(requestMap.get("ai_agent_instance_id").toString());
            request.setRegion((String) requestMap.getOrDefault("region", "cn-shanghai"));
            
            DigitalHumanInstanceResponseDto response = digitalHumanService.describeDigitalHumanInstance(request);
            
            if (response.getCode() == 200) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "success");
                result.put("call_log_url", response.getCallLogUrl());
                result.put("runtime_config", response.getRuntimeConfig());
                result.put("status", response.getStatus());
                result.put("template_config", response.getTemplateConfig());
                result.put("user_data", response.getUserData());
                result.put("request_id", response.getRequestId());
                
                return Result.success(result);
            } else {
                return Result.error(response.getMessage());
            }
        } catch (Exception e) {
            log.error("兼容API - 查询AI智能体实例异常: {}", e.getMessage(), e);
            return Result.error("查询AI智能体实例失败: " + e.getMessage());
        }
    }
}
